/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FlightView.java
 *
 * Created on 25-jan-2010, 16:25:55
 */
package View;

import Controller.Controller;
import Model.Flight;
import Util.CustomTableCellRenderer;
import Util.GenericTableModel;
import flyaway.FlyAWayView;
import java.awt.Color;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import javax.swing.table.TableColumnModel;
import org.jdesktop.application.FrameView;

/**
 *
 * @author Jeroen
 */
public class FlightView extends javax.swing.JInternalFrame implements Observer{

    private FrameView parentView;

    /**
     * Creates new form FlightView
     */
    public FlightView() {
        initComponents();
        Controller.Instance().addObserver(this);
        ButtonGroup buttonGrp = new ButtonGroup();
        buttonGrp.add(rButtonDate);
        buttonGrp.add(rButtonNumber);
        rButtonDate.setSelected(true);

        fillTable(Controller.Instance().getFlights());
        this.pack();
    }

    public void setParentView(FrameView pView) {
        this.parentView = pView;
    }

    public void update(Observable o, Object arg) {
        if (arg instanceof Flight) {
            ArrayList<Flight> flights = Controller.Instance().getFlights();
            fillTable(flights);
            ((FlyAWayView) this.parentView).renderMarqueeText();
        }
    }

    private void fillTable(ArrayList<Flight> flights) {
        GenericTableModel<Flight> flightsModel = new GenericTableModel<Flight>(flights);
        tblFlights.setModel(flightsModel);

        TableColumnModel tcm = tblFlights.getColumnModel();
        CustomTableCellRenderer tcr = new CustomTableCellRenderer();
        for (int it = 0; it < flightsModel.getColumnCount(); it++) {
            tcm.getColumn(it).setCellRenderer(tcr);
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblFlights = new javax.swing.JTable();
        btnCreate = new javax.swing.JButton();
        btnChange = new javax.swing.JButton();
        btnNew = new javax.swing.JButton();
        lblErrorMessage = new javax.swing.JLabel();
        btnSearch = new javax.swing.JButton();
        txtFieldSearch = new javax.swing.JTextField();
        rButtonDate = new javax.swing.JRadioButton();
        rButtonNumber = new javax.swing.JRadioButton();

        setClosable(true);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(flyaway.FlyAWayApp.class).getContext().getResourceMap(FlightView.class);
        setForeground(resourceMap.getColor("Form.foreground")); // NOI18N
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tblFlights.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tblFlights.setName("tblFlights"); // NOI18N
        jScrollPane1.setViewportView(tblFlights);

        btnCreate.setText(resourceMap.getString("btnCreate.text")); // NOI18N
        btnCreate.setName("btnCreate"); // NOI18N
        btnCreate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCreateActionPerformed(evt);
            }
        });

        btnChange.setText(resourceMap.getString("btnChange.text")); // NOI18N
        btnChange.setName("btnChange"); // NOI18N
        btnChange.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChangeActionPerformed(evt);
            }
        });

        btnNew.setText(resourceMap.getString("btnNew.text")); // NOI18N
        btnNew.setName("btnNew"); // NOI18N
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });

        lblErrorMessage.setText(resourceMap.getString("lblErrorMessage.text")); // NOI18N
        lblErrorMessage.setName("lblErrorMessage"); // NOI18N

        btnSearch.setText(resourceMap.getString("btnSearch.text")); // NOI18N
        btnSearch.setName("btnSearch"); // NOI18N
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });

        txtFieldSearch.setText(resourceMap.getString("txtFieldSearch.text")); // NOI18N
        txtFieldSearch.setName("txtFieldSearch"); // NOI18N

        rButtonDate.setText(resourceMap.getString("rButtonDate.text")); // NOI18N
        rButtonDate.setName("rButtonDate"); // NOI18N

        rButtonNumber.setText(resourceMap.getString("rButtonNumber.text")); // NOI18N
        rButtonNumber.setName("rButtonNumber"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblErrorMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 365, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(btnSearch, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnChange, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnCreate, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnNew, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtFieldSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(rButtonDate)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(rButtonNumber))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 463, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSearch)
                    .addComponent(txtFieldSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(rButtonDate)
                    .addComponent(rButtonNumber))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnCreate)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnChange)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnNew))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(lblErrorMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateActionPerformed
        CreateChangeFlightView ccfv = new CreateChangeFlightView(null);
        flyaway.FlyAWayApp app = (flyaway.FlyAWayApp) flyaway.FlyAWayApp.getApplication();
        app.getFlyAwayView().addFrame(ccfv);
    }//GEN-LAST:event_btnCreateActionPerformed

    private void btnChangeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChangeActionPerformed
        int index = tblFlights.getSelectedRow();
        if (index >= 0) {
            GenericTableModel<Flight> gtm = (GenericTableModel<Flight>) tblFlights.getModel();
            Flight f = gtm.getRow(index);
            CreateChangeFlightView ccfv = new CreateChangeFlightView(f);
            flyaway.FlyAWayApp app = (flyaway.FlyAWayApp) flyaway.FlyAWayApp.getApplication();
            app.getFlyAwayView().addFrame(ccfv);
        } else {
            lblErrorMessage.setText("Please select a row first");
        }
    }//GEN-LAST:event_btnChangeActionPerformed

    private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
        int index = tblFlights.getSelectedRow();
        if (index >= 0) {
            GenericTableModel<Flight> gtm = (GenericTableModel<Flight>) tblFlights.getModel();
            Flight f = gtm.getRow(index);
            Controller.Instance().removeFlight(f);
        } else {
            lblErrorMessage.setText("Please select a row first");
        }
    }//GEN-LAST:event_btnNewActionPerformed

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        lblErrorMessage.setText("");
        
        try {
            if (rButtonDate.isSelected()) {
                String searchDate = txtFieldSearch.getText();
                SimpleDateFormat sdf = new SimpleDateFormat(Flight.FLIGHTDATAFORMAT);
                fillTable(Controller.Instance().searchFlight(sdf.parse(searchDate)));
            } else if (rButtonNumber.isSelected()) {
                int searchNumber = Integer.parseInt(txtFieldSearch.getText());
                if (Controller.Instance().getFlightByNumber(searchNumber)) {
                    fillTable(Controller.Instance().searchFlight(searchNumber));
                }
            } else {
                lblErrorMessage.setForeground(Color.red);
                lblErrorMessage.setText("No search results found");
            }
        } catch (ParseException ex) {
            lblErrorMessage.setForeground(Color.red);
            lblErrorMessage.setText("Fill in a correct date in the format " + Flight.FLIGHTDATAFORMAT);
            Logger.getLogger(FlightView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NumberFormatException nfe) {
            lblErrorMessage.setForeground(Color.red);
            lblErrorMessage.setText("Please fill in a valid flight number");
            Logger.getLogger(FlightView.class.getName()).log(Level.SEVERE, null, nfe);
        }
    }//GEN-LAST:event_btnSearchActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnChange;
    private javax.swing.JButton btnCreate;
    private javax.swing.JButton btnNew;
    private javax.swing.JButton btnSearch;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblErrorMessage;
    private javax.swing.JRadioButton rButtonDate;
    private javax.swing.JRadioButton rButtonNumber;
    private javax.swing.JTable tblFlights;
    private javax.swing.JTextField txtFieldSearch;
    // End of variables declaration//GEN-END:variables

    
}
